package com.mdoya.exception;

import com.mdoya.response.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author mdoya
 * @version 1.0
 * @description:
 */
@Slf4j
@RestControllerAdvice
public class GlobaExceptiion {

    @ExceptionHandler(BusinessExceptiion.class)
    public ResultResponse handlerBusinessExceptiion(BusinessExceptiion e) {
        log.info("业务异常: {}", e.getMessage());
        return ResultResponse.error(e.getMessage());
    }

    /**
     *  mybatiPlus业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResultResponse handlerSql(SQLIntegrityConstraintViolationException e) {
        log.info("username unique: {}",e.getMessage());
        String message = e.getMessage();
        System.err.println(message);
        if (message.contains("Duplicate")) {
            String username = message.split(" ")[2];
            return ResultResponse.error(username + "已存在");
        }
        /*
        ### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException:
        Duplicate entry 'ff' for key 'employee.idx_username' ### The error may exist in com/mdoya/mapper/EmployeeMapper.java (best guess) ### The error may involve com.mdoya.mapper.EmployeeMapper.insert-Inline ### The error occurred while setting parameters ### SQL: INSERT INTO employee ( id, username, name, password, phone, sex, id_number, create_time, update_time, create_user, update_user ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ### Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'ff' for key 'employee.idx_username' ; Duplicate entry 'ff' for key 'employee.idx_username'; nested exception is java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'ff' for key 'employee.idx_username'
         */
        return ResultResponse.error("未知异常");
    }

   /* @ExceptionHandler(Exception.class)
    public ResultResponse handlerExceptiion(Exception e) {
        return ResultResponse.error(e.getMessage());
    }*/
}
